const { where } = require('sequelize')
const PostModel = require('../model/Post_model')
const { DeleteSpecified } = require('../utils/mass')

class PostService {
    async CreateArticle(data) {
        const { authorId, authorName, contentImage, content, image } = data
        const res = await PostModel.create({ authorId, authorName, contentImage: JSON.stringify(contentImage), content, image })
        return res
    }

    async selectArticle(params) {
        const { pageSize, pageNo } = params
        const limit = pageSize * 1
        const offset = (pageNo * 1 - 1) * pageSize
        const { count, rows } = await PostModel.findAndCountAll({
            attributes: ['id', 'content', 'contentImage', 'authorId', 'authorName', 'image', 'createdAt'],
            order: [
                ['createdAt', 'DESC'],
            ],
            offset,
            limit
        })
        rows.forEach((item) => {
            item.contentImage = JSON.parse(item.contentImage)
            item.contentImage = item.contentImage.map(item => item.image)
        })

        return { count, rows }
    }

    async deleteArticle(params) {
        try {
            const { id, authorId } = params
            const res = await PostModel.findOne({
                where: { id, authorId }
            })
            const deleteRes = await DeleteSpecified(JSON.parse(res.contentImage))
            if (deleteRes) {
                const result = await PostModel.destroy({
                    where: {
                        id, authorId
                    }
                })
                return result
            }


        } catch (error) {
            console.log(error);

        }

    }
}

module.exports = new PostService()